use crate::opt;
use std::{path::Path, fs::File, io::{self, Read}};
use cursive::view::{ViewWrapper, IntoBoxedView, View};
use cursive::views::{Dialog, DummyView, LinearLayout, TextView};
use cursive::Cursive;
use cursive_hexview::{DisplayState, HexView};

pub fn run(opt: opt::Opt) {
    let mut cur = Cursive::default();

    let explanation = TextView::new("Use the keys + - ↑ ↓ ← → 0-9 a-f for the HexView.\nUse q to exit.");
    let view = HexView::new_from_iter(read_file(opt.file()).expect("Cannot read file")).display_state(DisplayState::Enabled);

    cur.add_layer(
        Dialog::around(LinearLayout::vertical().child(explanation).child(DummyView).child(view)).title("HexView"),
    );
    cur.add_global_callback('q', |cur| cur.quit());
    cur.run();
}

fn read_file(path: &Path) -> Result<Vec<u8>, io::Error> {
    let mut file = File::open(path)?;
    let mut buf = Vec::new();
    file.read_to_end(&mut buf)?;
    Ok(buf)
}
